var $$ = Dom7;
var app  = new Framework7();
var browse_button = '';
var imgCount = 0;
var photoInfo = [];

//照片上传至阿里云
var accessid= 'LTAIWHx1kYTIUmN2';
var  accesskey= 'gOrhDX2oACRzBN8BzwoIOIdE9WzuwJ';
host = 'http://test22umake.oss-cn-beijing.aliyuncs.com';

g_dirname = ''
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

var policyText = {
  "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
  "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
  ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
  g_object_name_type = "random_name";
}


function get_suffix(filename) {
  pos = filename.lastIndexOf('.')
  suffix = ''
  if (pos != -1) {
    suffix = filename.substring(pos)
  }
  return suffix;
}

function calculate_object_name(filename)
{
  if (g_object_name_type == 'random_name')
  {
    var date=new Date;
    var year=date.getFullYear();
    var month=date.getMonth()+1;
    month =(month<10 ? "0"+month:month);
    var mydate = (year.toString()+month.toString());
    dir = "test/Help/image"+mydate;
    suffix = get_suffix(filename);
    g_object_name = dir+"/webApp_"+ Date.now()+ "_"+Math.round(Math.random() * 10000) + suffix;
  }
  return ''
}

function get_uploaded_object_name(filename)
{
  if(g_object_name_type == 'random_name')
  {
    return g_object_name
  }
}
function delect(imgsrc){
  app.dialog.create({
    title: '提示',
    text: '您确定要删除图片吗?',
    buttons: [
      {
        text: '取消',
      },
      {
        text: '确定',
        onClick:function () {
          imgCount--;
          $$(".selectfile").css("display","inline");
          var myp = document.getElementById('myp');
          var child = document.getElementById(imgsrc);
          myp.removeChild(child);
        }
      },
    ],
  }).open();
}

function set_upload_param(up, filename, ret)
{
  g_object_name = g_dirname;
  if (filename != '') {
    suffix = get_suffix(filename)
    calculate_object_name(filename)
  }
  new_multipart_params = {
    'key' : g_object_name,
    'policy': policyBase64,
    'OSSAccessKeyId': accessid,
    'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
    'signature': signature,
  };
  up.setOption({
    'url': host,
    'multipart_params': new_multipart_params
  });
  up.start();
}

var uploader = new plupload.Uploader({
  //accept:"image/*",
  runtimes : 'html5,flash,silverlight,html4',
  browse_button : 'selectfile',
  multi_selection: false,
  container: $$('#container')[0],
  flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
  silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
  url : 'http://oss.aliyuncs.com',
  resize: { width: 320, height: 240, quality: 80 },
  filters: [{title: "Image files",extensions: "jpg,gif,png,jpeg"}],//图片限制
  init: {
    PostInit: function() {
      $$('#selectfile').on('click', function(){
        set_upload_param(uploader, '', false);
        return false;
      });
    },

    FilesAdded: function(up, files) {
      // console.log(files[0].type)
      if(files[0].type != 'image/jpeg' && files[0].type != 'image/png' && files[0].type != 'image/jpg') {
        app.dialog.create({
          title: '提示',
          text: "请上传图片",
          buttons: [
            {
              text: '确定'
            }
          ],
        }).open();
        return;
      }
      var paramsA = Date.now();

      var bigImg = document.createElement("img");     //创建一个img元素
      bigImg.src= "./img/background_image.jpg";   //给img元素的src属性赋值
      bigImg.width="50";  //320个像素 不用加px
      bigImg.height="50";
      bigImg.id= paramsA;
      bigImg.setAttribute("style", "padding-right:10px");
      var myp = document.getElementById('myp'); //获得dom对象
      myp.appendChild(bigImg);    //为dom添加子元素img
      $$('#selectfile').click();
      imgCount++;
      if(imgCount === 3) {
        //是否隐藏添加按钮
        $$(".selectfile").css("display","none");
      }
      plupload.each(files, function(file) {
        var preloader = new mOxie.Image();
        preloader.onload = function() {
          preloader.downsize(300, 300); //先压缩一下要预览的图片,宽300，高300
          var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
          var myp = document.getElementById('myp');
          var child=document.getElementById(paramsA);
          child.setAttribute("src",imgsrc);
          child.setAttribute("id",imgsrc);
          child.width="50";  //320个像素 不用加px
          child.height="50";
          child.onclick= function () {delect(imgsrc)};
          preloader.destroy();
          preloader = null;
        };
        preloader.load(file.getSource());
      });
      window.setTimeout("functionTimeout();",1000);
    },

    BeforeUpload: function(up, file) {
      app.preloader.show();
      check_object_radio();
      set_upload_param(up, file.name, true);
    },

    UploadProgress: function(up, file) {
      if(file.percent === 100){
        app.preloader.hide();
      }
    },

    FileUploaded: function(up, file, info) {
      if (info.status == 200)
      {
        photoInfo.push(g_object_name);
      }
      else
      {
        console.log(info.response)
        app.dialog.create({
          title: '提示',
          text: "上传失败，请稍后再试",
          buttons: [
            {
              text: '确定'
            }
          ],
        }).open();

      }
    },

    Error: function(up, err) {
      console.log(err.response)
      app.dialog.create({
        title: '提示',
        text: "上传失败，请稍后再试",
        buttons: [
          {
            text: '确定'
          }
        ],
      }).open();
    }
  }
});



function functionTimeout(){
  uploader.refresh();
}

//uploader.init();
uploader.init();
